package net.eldeen.stockhack.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

public class ForesightWebConnect implements WebConnect {

  private static final Logger LOGGER = Logger.getLogger(ForesightWebConnect.class);

  private HttpClient httpClient;
  private final String baseUri;
  private final String username;
  private final String password;

  public ForesightWebConnect(String baseUri, String username, String password) {
    httpClient = new DefaultHttpClient();
    this.baseUri = baseUri;
    this.username = username;
    this.password = password;

  }

  /* (non-Javadoc)
   * @see net.eldeen.stockhack.service.WebConnect#initialGet()
   */
  private boolean initialGet() throws ClientProtocolException, IOException {
    HttpGet httpGet = new HttpGet(baseUri);

    HttpResponse httpResponse = httpClient.execute(httpGet);

    HttpEntity entity = httpResponse.getEntity();
    if (null != entity) {
      entity.consumeContent();
    }

    return httpResponse.getStatusLine().getStatusCode() == 200;
  }

  /* (non-Javadoc)
   * @see net.eldeen.stockhack.service.WebConnect#login()
   */
  public boolean login() throws ClientProtocolException, IOException {

    if (initialGet()) {
      LOGGER.debug("Logged in");
      HttpPost httpPost = new HttpPost(baseUri + "trader");//TODO set this
      List<NameValuePair> nvps = new ArrayList<NameValuePair>();
      //action=login&username="+username+"&password="+password
      nvps.add(new BasicNameValuePair("action", "login"));
      nvps.add(new BasicNameValuePair("username", username));//TODO set this
      nvps.add(new BasicNameValuePair("password", password));//TODO set this

      httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      HttpResponse httpResponse = httpClient.execute(httpPost);

      HttpEntity entity = httpResponse.getEntity();
      if (null != entity) {
        entity.consumeContent();
      }

      return httpResponse.getStatusLine().getStatusCode() == 200;
    } else {
      return false;
    }
  }

  public String fetchStocksData() throws ClientProtocolException, IOException {
    StringBuffer stocksData = null;
    HttpGet httpGet = new HttpGet(baseUri + "trader/data.xml");

    HttpResponse httpResponse = httpClient.execute(httpGet);

    HttpEntity entity = httpResponse.getEntity();
    if (null != entity) {
      stocksData = new StringBuffer((int) entity.getContentLength());
      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
      while (bufferedReader.ready()) {
        stocksData.append(bufferedReader.readLine());
      }
      entity.consumeContent();
    }

    return (stocksData!=null ? stocksData.toString() : "");
  }
  
//  public InputStream fetchStocksDataStream() throws IllegalStateException, ClientProtocolException, IOException {
//	  HttpGet httpGet = new HttpGet(baseUri + "trader/data.xml");
//
//	  HttpResponse httpResponse = httpClient.execute(httpGet);
//
//	  HttpEntity entity = httpResponse.getEntity();
//    
//	  return entity.getContent();
//	    
//  }

  public boolean logout() throws ClientProtocolException, IOException {
    String logoutUrl = baseUri + "trader/logout/index";
    HttpGet httpGet = new HttpGet(logoutUrl);

    HttpResponse httpResponse = httpClient.execute(httpGet);

    HttpEntity entity = httpResponse.getEntity();
    if (null != entity) {
      entity.consumeContent();
    }
    boolean isGoodStatus = httpResponse.getStatusLine().getStatusCode() == 200;
    shutdown();

    return isGoodStatus;
  }

  public int tradeStock(String stockName, boolean buy, int shares, BigDecimal price) {
    // TODO Auto-generated method stub
    return 0;
  }

  /**
   * When HttpClient instance is no longer needed,
   * shut down the connection manager to ensure
   * immediate deallocation of all system resources
   */
  private void shutdown() {
    httpClient.getConnectionManager().shutdown();
  }

}
